package labuladong.滑动窗口;

import java.util.HashMap;
import java.util.Map;

public class 最长无重复子串 {
    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("abcabcbb"));
        System.out.println(lengthOfLongestSubstring("bbbbbbb"));
        System.out.println(lengthOfLongestSubstring("pwwkew"));
    }

    public static int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> window = new HashMap<>();
        int left = 0, right = 0;
        int len = Integer.MIN_VALUE;
        while (right < s.length()) {
            char c = s.charAt(right);
            right ++;
            window.put(c, window.getOrDefault(c, 0)+1);
            while (window.get(c) > 1) {
                char c1 = s.charAt(left);
                left++;
                window.put(c1, window.get(c1)-1);
                if (window.get(c1) <= 0) {
                    window.remove(c1);
                }
            }
            len = (right-left) > len ? (right-left) : len;
        }
        return len;
    }
}
